from flask_restful import Resource,reqparse,request
from flask_shop.order import order_bp,order_api
from flask_shop import models
from flask_shop import db

class Orders(Resource):
    def get(self):
       parser = reqparse.RequestParser()
       parser.add_argument('id',type=str,location='args')
       args = parser.parse_args()
       id = args.get('id')
       if id:
            order = models.Order.query.filter(models.Order.id == id).all()
       else:
            order = models.Order.query.all()
       return {'status':200,'msg':'获取成功','data':[o.to_dict() for o in order]}

order_api.add_resource(Orders,'/orders/')

class Order(Resource):
    def get(self,id):
        order = models.Order.query.get(id)
        return {'status':200,'msg':'获取成功','data':order.to_dict()}

order_api.add_resource(Order,'/order/<int:id>/')

from sqlalchemy import text

class Express(Resource):
    def get(self):
        id = request.args.get('oid')
        sql = 'select id,oid,content,update_time from t_express where oid = ' + str(id) + ' order by update_time desc'
        list = db.session.execute(text(sql)).all()
        data = []
        for d in list:
            data.append(to_dict(d))
        return {'status':200,'msg':'获取成功','data':data}

    def post(self):
        sql = 'select level,count(0) from t_category group by level'
        dataList = db.session.execute(text(sql)).all()
        data = {
            'name':'分类数量',
            'x':[f'{i[0]}级分类' for i in dataList],
            'y':[i[1] for i in dataList]
        }
        return {'status':200,'msg':'获取成功','data':data}

def to_dict(self):
    return {
        'id': self.id,
        'oid': self.oid,
        'content': self.content,
        'update_time': self.update_time,
}       

order_api.add_resource(Express,'/express/')